package fr.generali.accueilclient.gwt.client.editor;

import java.util.HashMap;
import java.util.List;
import java.util.Map.Entry;

import com.google.gwt.editor.client.LeafValueEditor;
import com.google.gwt.uibinder.client.UiConstructor;
import com.google.gwt.user.client.ui.InsertPanel;
import com.google.gwt.user.client.ui.RadioButton;

public class RadioButonGroupEditor implements LeafValueEditor<String> {

	private final HashMap<String, RadioButton> radioButtons = new HashMap<String, RadioButton>();
	
	private final InsertPanel panel;

	@UiConstructor
	public RadioButonGroupEditor(List<RadioButton> radioButtonList, InsertPanel panel) {

		this.panel = panel;
		
		for (RadioButton radioButton: radioButtonList) {
			
			panel.add(radioButton);
			
			radioButtons.put(radioButton.getFormValue(), radioButton);
		}
	}

	@Override
	public void setValue(String value) {
		if (value == null)
			return;

		int index = panel.getWidgetIndex(radioButtons.get(value));

		RadioButton radioBtn = (RadioButton) panel.getWidget(index);

		radioBtn.setValue(true);
	}

	@Override
	public String getValue() {
		for (Entry<String, RadioButton> e : radioButtons.entrySet()) {
			if (e.getValue().getValue()) {
				return e.getKey();
			}
		}
		return null;
	}
}